<template>
  <view class="footer">
    <view
      v-for="item in navItems"
      :key="item.path"
      class="footer-item"
      :class="{ active: activeRoute === item.path }"
      @tap="handleSwitchTab(item.path)"
    >
      <u-icon :name="item.icon" size="48" :color="activeRoute === item.path ? activeColor : inactiveColor"></u-icon>
      <text class="footer-text">{{ item.label }}</text>
    </view>
  </view>
</template>

<script setup>
import { computed, ref, onMounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'

defineOptions({
  name: 'CustomTabBar'
})

const activeColor = '#e54d42'
const inactiveColor = '#999'

const navItems = [
  { label: '首页', icon: 'home', path: '/pages/index/index' },
  { label: '产品', icon: 'grid', path: '/pages/product/index' },
  { label: '社区', icon: 'chat', path: '/pages/community/index' },
  { label: '我的', icon: 'account', path: '/pages/mine/index' }
]

const currentPath = ref(navItems[0].path)

const resolveCurrentPath = () => {
  const pages = getCurrentPages()
  const current = pages[pages.length - 1]?.route
  currentPath.value = current ? `/${current}` : navItems[0].path
}

onMounted(() => {
  resolveCurrentPath()
})

onShow(() => {
  resolveCurrentPath()
})

const activeRoute = computed(() => currentPath.value)

const handleSwitchTab = (targetPath) => {
  if (targetPath === activeRoute.value) {
    return
  }

  uni.switchTab({
    url: targetPath
  })
}
</script>

<style lang="scss">
@import './index.scss';
</style>

